import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import CitySelector from '../../components/CitySelector';

// 定义地址类型
interface Address {
  id: number;
  name: string;
  address: string;
  location: {
    lng: number;
    lat: number;
  };
}

// 定义城市类型
interface City {
  name: string;
  location: {
    lng: number;
    lat: number;
  };
}

// 定义城市列表类型
interface CitiesByLetter {
  [key: string]: City[];
}

// 定义城市地址数据类型
interface CityAddresses {
  [key: string]: Address[];
}

// 模拟地址数据
const mockAddresses: Address[] = [
  {
    id: 1,
    name: '万达广成',
    address: '北京市石景山区万达广成',
    location: { lng: 116.184479, lat: 39.914511 }
  },
  {
    id: 2,
    name: '万达广成',
    address: '北京市石景山区万达广成',
    location: { lng: 116.185479, lat: 39.915511 }
  },
  {
    id: 3,
    name: '万达广成',
    address: '北京市石景山区万达广成',
    location: { lng: 116.186479, lat: 39.916511 }
  },
  {
    id: 4,
    name: '万达广成',
    address: '北京市石景山区万达广成',
    location: { lng: 116.187479, lat: 39.917511 }
  }
];

// 热门城市数据
const hotCities = [
  { name: '北京', location: { lng: 116.397428, lat: 39.90923 } },
  { name: '河北', location: { lng: 114.502461, lat: 38.045474 } },
  { name: '保定', location: { lng: 115.482331, lat: 38.867657 } },
  { name: '上海', location: { lng: 121.472644, lat: 31.231706 } },
  { name: '广州', location: { lng: 113.280637, lat: 23.125178 } },
  { name: '深圳', location: { lng: 114.085947, lat: 22.547 } },
  { name: '杭州', location: { lng: 120.153576, lat: 30.287459 } },
  { name: '成都', location: { lng: 104.065735, lat: 30.659462 } },
  { name: '重庆', location: { lng: 106.504962, lat: 29.533155 } },
  { name: '西安', location: { lng: 108.948024, lat: 34.263161 } }
];

// 按拼音首字母排序的城市数据
const citiesByLetter: CitiesByLetter = {
  'B': [
    { name: '北京', location: { lng: 116.397428, lat: 39.90923 } },
    { name: '保定', location: { lng: 115.482331, lat: 38.867657 } }
  ],
  'C': [
    { name: '成都', location: { lng: 104.065735, lat: 30.659462 } },
    { name: '重庆', location: { lng: 106.504962, lat: 29.533155 } }
  ],
  'G': [
    { name: '广州', location: { lng: 113.280637, lat: 23.125178 } }
  ],
  'H': [
    { name: '杭州', location: { lng: 120.153576, lat: 30.287459 } },
    { name: '合肥', location: { lng: 117.283042, lat: 31.86119 } }
  ],
  'N': [
    { name: '南京', location: { lng: 118.767413, lat: 32.041544 } },
    { name: '宁波', location: { lng: 121.549792, lat: 29.868388 } }
  ],
  'S': [
    { name: '上海', location: { lng: 121.472644, lat: 31.231706 } },
    { name: '深圳', location: { lng: 114.085947, lat: 22.547 } }
  ],
  'T': [
    { name: '天津', location: { lng: 117.190182, lat: 39.125596 } }
  ],
  'W': [
    { name: '武汉', location: { lng: 114.298572, lat: 30.584355 } }
  ],
  'X': [
    { name: '西安', location: { lng: 108.948024, lat: 34.263161 } }
  ]
};

// 模拟不同城市的地址数据
const cityAddresses: CityAddresses = {
  '北京': [
    { id: 1, name: '天安门', address: '北京市东城区天安门广场', location: { lng: 116.397428, lat: 39.90923 } },
    { id: 2, name: '故宫博物院', address: '北京市东城区景山前街4号', location: { lng: 116.403414, lat: 39.917544 } },
    { id: 3, name: '三里屯', address: '北京市东城区景山前街4号', location: { lng: 116.454552, lat: 39.935345 } }

  ],
  '上海': [
    { id: 3, name: '外滩', address: '上海市黄浦区中山东一路', location: { lng: 121.490317, lat: 31.233844 } },
    { id: 4, name: '东方明珠', address: '上海市浦东新区世纪大道1号', location: { lng: 121.499741, lat: 31.239702 } }
  ],
  '广州': [
    { id: 5, name: '广州塔', address: '广州市海珠区阅江西路222号', location: { lng: 113.319042, lat: 23.106216 } },
    { id: 6, name: '陈家祠', address: '广州市荔湾区中山七路', location: { lng: 113.256673, lat: 23.125624 } }
  ],
  '深圳': [
    { id: 7, name: '世界之窗', address: '深圳市南山区华侨城深南大道', location: { lng: 113.979564, lat: 22.534832 } },
    { id: 8, name: '东部华侨城', address: '深圳市盐田区大梅沙东部华侨城', location: { lng: 114.287724, lat: 22.631964 } }
  ]
};

// 为其他城市生成默认数据
Object.keys(citiesByLetter).forEach(letter => {
  citiesByLetter[letter].forEach((city: City) => {
    if (!cityAddresses[city.name]) {
      cityAddresses[city.name] = [
        {
          id: 1,
          name: `万达广场(${city.name}中心店)`,
          address: `${city.name}市中心万达广场`,
          location: city.location
        },
        {
          id: 2,
          name: `万达广场(${city.name}东区店)`,
          address: `${city.name}市东区万达广场`,
          location: {
            lng: city.location.lng + 0.02,
            lat: city.location.lat + 0.01
          }
        },
        {
          id: 3,
          name: `万达广场(${city.name}西区店)`,
          address: `${city.name}市西区万达广场`,
          location: {
            lng: city.location.lng - 0.02,
            lat: city.location.lat - 0.01
          }
        }
      ] as Address[];
    }
  });
});

declare global {
  interface Window {
    AMap: any;
    _AMapSecurityConfig: {
      securityJsCode: string;
    };
  }
}

// 辅助函数：创建坐标元组
function createCoordinates(lng: number, lat: number): [number, number] {
  return [lng, lat];
}

export default function Xiugaidingwei() {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchText, setSearchText] = useState('');
  const [currentCity, setCurrentCity] = useState('北京');
  const [addresses, setAddresses] = useState(cityAddresses['北京']);
  const [selectedLocation, setSelectedLocation] = useState<{ lng: number; lat: number }>(cityAddresses['北京'][0].location);
  const [currentAddress, setCurrentAddress] = useState('');
  const [mapLoaded, setMapLoaded] = useState(false);
  const [showCitySelector, setShowCitySelector] = useState(false);
  const [isLocating, setIsLocating] = useState(false);
  const mapRef = useRef<any>(null);
  const markerRef = useRef<any>(null);
  const mapContainerRef = useRef<HTMLDivElement>(null);

  // 使用IP定位
  const useCitySearch = () => {
    try {
      // 使用 Geolocation 的 getCityInfo 方法获取城市信息
      const geolocation = new window.AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 15000,
        convert: true, // 自动偏移坐标
        extensions: 'all'
      });

      // 直接使用 getCurrentPosition 方法，它会自动降级到 IP 定位
      geolocation.getCurrentPosition((status: string, result: any) => {
        if (status === 'complete') {
          const { position } = result;
          // 使用逆地理编码获取详细地址
          const geocoder = new window.AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          });

          geocoder.getAddress([position.lng, position.lat], (status: string, addressResult: any) => {
            if (status === 'complete' && addressResult.regeocode) {
              const { addressComponent } = addressResult.regeocode;
              const city = addressComponent.city || addressComponent.province;

              handleLocationSuccess({
                position: {
                  lng: position.lng,
                  lat: position.lat
                }
              });
              setCurrentCity(city);
            } else {
              // 如果逆地理编码失败，仍然使用获取到的坐标
              handleLocationSuccess({
                position: {
                  lng: position.lng,
                  lat: position.lat
                }
              });
            }
          });
        } else {
          // 定位失败，使用默认位置（北京）
          console.warn('定位失败，使用默认位置');
          handleLocationSuccess({
            position: {
              lng: 116.397428,
              lat: 39.90923
            }
          });
          setCurrentCity('北京');
        }
        setIsLocating(false);
      });
    } catch (error) {
      console.error('定位服务初始化失败:', error);
      // 使用默认位置
      handleLocationSuccess({
        position: {
          lng: 116.397428,
          lat: 39.90923
        }
      });
      setCurrentCity('北京');
      setIsLocating(false);
    }
  };

  // 初始化地图
  useEffect(() => {
    const initMap = () => {
      if (mapContainerRef.current && !mapRef.current && window.AMap) {
        try {
          // 创建地图实例
          const map = new window.AMap.Map(mapContainerRef.current, {
            zoom: 14,
            center: [selectedLocation.lng, selectedLocation.lat],
            resizeEnable: true
          });
          mapRef.current = map;

          // 创建标记
          const marker = new window.AMap.Marker({
            position: [selectedLocation.lng, selectedLocation.lat],
            draggable: true,
            cursor: 'move',
            animation: 'AMAP_ANIMATION_DROP'
          });

          marker.setMap(map);
          markerRef.current = marker;

          // 监听标记拖动结束事件
          marker.on('dragend', () => {
            const position = marker.getPosition();
            const newLocation = {
              lng: position.lng,
              lat: position.lat
            };
            setSelectedLocation(newLocation);
            updateAddressFromLocation(newLocation);
          });

          // 添加地图控件
          map.addControl(new window.AMap.Scale({
            position: 'LB'
          }));
          map.addControl(new window.AMap.ToolBar({
            position: 'RB'
          }));

          setMapLoaded(true);
        } catch (error) {
          console.error('地图初始化失败:', error);
        }
      }
    };

    if (window.AMap) {
      initMap();
    } else {
      // 等待地图加载完成
      const checkAMap = setInterval(() => {
        if (window.AMap) {
          initMap();
          clearInterval(checkAMap);
        }
      }, 100);

      // 5秒后如果还没加载成功，清除检查
      setTimeout(() => {
        clearInterval(checkAMap);
        if (!window.AMap) {
          console.error('地图 API 加载失败');
        }
      }, 5000);
    }

    return () => {
      if (mapRef.current) {
        mapRef.current.destroy();
        mapRef.current = null;
      }
    };
  }, [selectedLocation]);

  // 更新地址信息
  const updateAddressFromLocation = (location: { lng: number; lat: number }) => {
    if (!window.AMap) return;

    const geocoder = new window.AMap.Geocoder({
      radius: 1000,
      extensions: "all"
    });

    geocoder.getAddress([location.lng, location.lat], (status: string, result: any) => {
      if (status === 'complete' && result.info === 'OK') {
        const address = result.regeocode.formattedAddress;
        setCurrentAddress(address);
        // 更新城市信息
        const addressComponent = result.regeocode.addressComponent;
        if (addressComponent.city) {
          setCurrentCity(addressComponent.city);
        } else if (addressComponent.province) {
          setCurrentCity(addressComponent.province);
        }
      } else {
        console.error('地址解析失败');
      }
    });
  };

  // 获取当前位置
  const getCurrentLocation = () => {
    setIsLocating(true);

    // 创建定位对象
    const geolocation = new window.AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 15000,
      buttonPosition: 'RB',
      buttonOffset: new window.AMap.Pixel(10, 20),
      zoomToAccuracy: true,
      GeoLocationFirst: true,
    });

    // 浏览器定位
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          // 浏览器定位成功
          handleLocationSuccess({
            position: {
              lng: position.coords.longitude,
              lat: position.coords.latitude
            }
          });
        },
        () => {
          // 浏览器定位失败，使用高德定位
          useAMapGeolocation();
        },
        {
          enableHighAccuracy: true,
          timeout: 15000,
          maximumAge: 0
        }
      );
    } else {
      // 不支持浏览器定位，使用高德定位
      useAMapGeolocation();
    }
  };

  // 使用高德地图定位
  const useAMapGeolocation = () => {
    const geolocation = new window.AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 15000,
      GeoLocationFirst: true
    });

    geolocation.getCurrentPosition((status: string, result: any) => {
      if (status === 'complete') {
        handleLocationSuccess(result);
      } else {
        // 定位失败，使用IP定位
        useCitySearch();
      }
    });
  };

  // 处理定位成功
  const handleLocationSuccess = (result: any) => {
    const { lng, lat } = result.position;
    const newLocation = { lng, lat };
    setSelectedLocation(newLocation);

    if (mapRef.current && markerRef.current) {
      mapRef.current.setCenter([lng, lat]);
      markerRef.current.setPosition([lng, lat]);
      updateAddressFromLocation(newLocation);
    }

    setIsLocating(false);
  };

  // 处理搜索
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchText(value);

    if (!value.trim()) {
      setAddresses(cityAddresses[currentCity]);
      return;
    }

    // 在当前城市的地址中搜索
    const filtered: Address[] = cityAddresses[currentCity].filter((item: Address) =>
      item.name.toLowerCase().includes(value.toLowerCase()) ||
      item.address.toLowerCase().includes(value.toLowerCase())
    );
    setAddresses(filtered);
  };

  // 处理城市选择
  const handleCitySelect = (city: string) => {
    setCurrentCity(city);
    setShowCitySelector(false);

    // 更新地址列表为选中城市的地址
    if (cityAddresses[city]) {
      setAddresses(cityAddresses[city]);
    }

    // 找到选中城市的位置信息
    let cityLocation: { lng: number; lat: number } | undefined;

    // 先在热门城市中查找
    const hotCity = hotCities.find(c => c.name === city);
    if (hotCity) {
      cityLocation = hotCity.location;
    } else {
      // 在按字母分类的城市中查找
      for (const letter in citiesByLetter) {
        const foundCity = citiesByLetter[letter].find(c => c.name === city);
        if (foundCity) {
          cityLocation = foundCity.location;
          break;
        }
      }
    }

    // 如果找到了城市位置，更新地图
    if (cityLocation && mapRef.current) {
      setSelectedLocation(cityLocation);

      // 更新地图视图
      mapRef.current.setCenter([cityLocation.lng, cityLocation.lat]);
      mapRef.current.setZoom(11); // 设置适当的缩放级别以显示整个城市

      if (markerRef.current) {
        markerRef.current.setPosition([cityLocation.lng, cityLocation.lat]);
      }

      // 使用逆地理编码获取详细地址
      mapRef.current.plugin('AMap.Geocoder', () => {
        const geocoder = new window.AMap.Geocoder({
          city: city // 指定查询的城市
        });

        geocoder.getAddress([cityLocation.lng, cityLocation.lat], (status: string, result: any) => {
          if (status === 'complete' && result.info === 'OK') {
            setCurrentAddress(result.regeocode.formattedAddress);
          }
        });
      });
    }
  };

  // 处理地址选择
  const handleSelectAddress = (address: Address) => {
    setSelectedLocation(address.location);
    setCurrentAddress(address.address);

    // 更新地图中心点和标记位置
    if (mapRef.current && markerRef.current) {
      mapRef.current.setCenter([address.location.lng, address.location.lat]);
      markerRef.current.setPosition([address.location.lng, address.location.lat]);
      mapRef.current.setZoom(15); // 放大到更详细的级别
    }
  };

  // 根据城市名获取城市位置
  const getCityLocation = (cityName: string): { lng: number; lat: number } | undefined => {
    // 先在热门城市中查找
    const hotCity = hotCities.find(c => c.name === cityName);
    if (hotCity) {
      return hotCity.location;
    }

    // 在按字母分类的城市中查找
    for (const letter in citiesByLetter) {
      const foundCity = citiesByLetter[letter].find(c => c.name === cityName);
      if (foundCity) {
        return foundCity.location;
      }
    }

    return undefined;
  };

  return (
    <div style={{ background: '#fff', minHeight: '100vh', fontFamily: 'sans-serif' }}>
      {/* 顶部导航栏 */}
      <div style={{
        padding: '16px',
        borderBottom: '1px solid #eee',
        display: 'flex',
        alignItems: 'center',
        position: 'sticky',
        top: 0,
        background: '#fff',
        zIndex: 1000
      }}>
        <button
          onClick={() => navigate(-1)}
          style={{
            background: 'none',
            border: 'none',
            fontSize: 20,
            cursor: 'pointer',
            padding: '0 12px',
            color: '#333'
          }}
          aria-label="返回"
        >
          ←
        </button>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 18, fontWeight: 'bold' }}>
          修改定位
        </div>
      </div>

      {/* 搜索区域 */}
      <div style={{
        display: 'flex',
        padding: '12px 16px',
        borderBottom: '1px solid #eee',
        alignItems: 'center',
        background: '#f5f5f5'
      }}>
        <div
          onClick={() => setShowCitySelector(true)}
          style={{
            marginRight: 12,
            fontSize: 14,
            color: '#333',
            padding: '6px 12px',
            background: '#fff',
            borderRadius: 4,
            border: '1px solid #eee',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            gap: 4
          }}
        >
          {currentCity}
          <span style={{ fontSize: 12, color: '#999' }}>▼</span>
        </div>
        <div style={{
          flex: 1,
          display: 'flex',
          alignItems: 'center',
          background: '#fff',
          borderRadius: 4,
          padding: '0 12px',
          border: '1px solid #eee'
        }}>
          <input
            value={searchText}
            onChange={handleSearch}
            placeholder="请输入您的地址"
            style={{
              flex: 1,
              border: 'none',
              padding: '8px 0',
              fontSize: 14,
              outline: 'none'
            }}
          />
          {searchText && (
            <button
              onClick={() => {
                setSearchText('');
                setAddresses(mockAddresses);
              }}
              style={{
                background: 'none',
                border: 'none',
                color: '#999',
                padding: '0 4px',
                cursor: 'pointer'
              }}
            >
              ×
            </button>
          )}
        </div>
      </div>

      {/* 当前位置按钮 */}
      <div style={{
        padding: '8px 16px',
        borderBottom: '1px solid #eee'
      }}>
        <button
          onClick={getCurrentLocation}
          disabled={isLocating || !mapLoaded}
          style={{
            width: '100%',
            padding: '8px',
            background: isLocating ? '#ccc' : '#1890ff',
            color: '#fff',
            border: 'none',
            borderRadius: '4px',
            fontSize: '14px',
            cursor: isLocating ? 'not-allowed' : 'pointer',
            position: 'relative'
          }}
        >
          {isLocating ? '正在获取位置...' : '获取当前位置'}
        </button>
      </div>

      {/* 地图区域 */}
      <div
        ref={mapContainerRef}
        style={{
          height: '350px', // 增加地图高度
          width: '100%',
          position: 'relative',
          overflow: 'hidden'
        }}
      />

      {/* 当前地址显示 */}
      {currentAddress && (
        <div style={{
          padding: '12px 16px',
          borderBottom: '1px solid #eee',
          fontSize: '14px',
          color: '#666'
        }}>
          当前位置: {currentAddress}
        </div>
      )}

      {/* 地址列表 */}
      <div style={{ padding: '0 16px' }}>
        {addresses.map((address) => (
          <div
            key={address.id}
            onClick={() => handleSelectAddress(address)}
            style={{
              padding: '16px 0',
              borderBottom: '1px solid #eee',
              cursor: 'pointer'
            }}
          >
            <div style={{ fontSize: 16, marginBottom: 4 }}>{address.name}</div>
            <div style={{ fontSize: 14, color: '#666' }}>{address.address}</div>
          </div>
        ))}
      </div>

      {/* 城市选择器 */}
      <CitySelector
        visible={showCitySelector}
        onClose={() => setShowCitySelector(false)}
        onSelect={handleCitySelect}
        currentCity={currentCity}
      />
    </div>
  );
}
